from django import forms
from .models import Rating
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class RatingForm(forms.ModelForm):
    class Meta:
        model = Rating
        fields = ['rating', 'comment']
        widgets = {
            'rating': forms.Select(choices=[(i, i) for i in range(1, 6)]),
            'comment': forms.Textarea(attrs={'rows': 3}),
        }

class MovieSearchForm(forms.Form):
    query = forms.CharField(required=False, label='搜索电影',
                           widget=forms.TextInput(attrs={'placeholder': '输入电影名称或关键词'}))

class SignUpForm(UserCreationForm):
    email = forms.EmailField(max_length=254, required=True, help_text='必填。请输入有效的电子邮件地址。')
    
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')
    
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("该用户名已被使用，请选择其他用户名。")
        return username
    
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("该电子邮件已被注册，请使用其他电子邮件或尝试重置密码。")
        return email 